package middleware

import (
	"duoke/context"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/yaml"
	"github.com/gin-gonic/gin"
	"strings"
)

func Init() gin.HandlerFunc {
	config := yaml.GetConfig()
	return func(c *gin.Context) {
		// 全局变量初始化
		scheme := "https://"
		if config.Request.Scheme == "" {
			if c.Request.TLS != nil {
				scheme = "https://"
			} else {
				scheme = "http://"
			}
		} else {
			scheme = config.Request.Scheme
		}

		if config.Request.Domain != "" {
			c.Request.Host = config.Request.Domain
		}
		// fmt.Println(c.Request)
		url := strings.Join([]string{scheme, c.Request.Host, c.Request.RequestURI}, "")
		context.InitGlobal(scheme, c.Request.Host, url, c.FullPath(), c.ClientIP())
		// 初始化账户
		acid := c.Request.Header.Get("D-Acid")
		if acid != "" {
			c.Set("account", service.AccountStruct{Id: gconv.Int(acid)})
		}
	}
}
